package com.combetter.changxing.ui.dialog;

import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.jakewharton.rxbinding2.view.RxView;
import com.combetter.changxing.R;
import com.combetter.changxing.databinding.DialogCityListBinding;
import com.combetter.changxing.model.City;
import com.combetter.changxing.net.HttpRequest;
import com.combetter.changxing.net.service.APIService;
import com.combetter.changxing.util.Check;
import com.combetter.changxing.util.DeviceUtils;
import com.combetter.changxing.util.LogUtil;
import com.combetter.changxing.util.ResUtils;
import com.combetter.changxing.util.ToastUtils;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.combetter.changxing.constanst.Constants.REUEST_CODDE;

/**
 * 城市列表Dialog
 * <p>
 * Created by 深圳唐龙飞讯科技有限公司 on 2018/7/9.
 */
public class CityListDialog extends DialogFragment {
    //性别Id
    public static int cityId = 7;
    private DialogCityListBinding mBinding;
    private CityAdapter adapter;
    private List<City> cities;
    private int count = 0;  //判断是否最后一级

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mBinding = DataBindingUtil.inflate(inflater, R.layout.dialog_city_list, container, false);
        getDialog().setCanceledOnTouchOutside(false); // 外部点击取消

        // 设置宽度为屏宽, 靠近屏幕底部。
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        window.setAttributes(lp);

        slideToUp(mBinding.getRoot());
        initVies();
        onClick();
        getCity(0);
        return mBinding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        int width = (int) DeviceUtils.getScreenWidth(getContext());
        int height = ResUtils.getDimens(getContext(), R.dimen.DIMEN_800PX);
        getDialog().getWindow().setLayout(width, height);
    }

    /**
     * 初始化控件
     */
    private void initVies() {
        cities = new ArrayList<>();
        adapter = new CityAdapter(cities);
        mBinding.cityRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        mBinding.cityRecycler.setAdapter(adapter);
    }

    private void onClick() {
        RxView.clicks(mBinding.ivCancel).subscribe(o -> dismiss());
    }

    public static void slideToUp(View view) {
        Animation slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                1.0f, Animation.RELATIVE_TO_SELF, 0.0f);

        slide.setDuration(400);
        slide.setFillAfter(true);
        slide.setFillEnabled(true);
        view.startAnimation(slide);

        slide.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    class CityAdapter extends BaseQuickAdapter<City, BaseViewHolder> {

        public CityAdapter(@Nullable List<City> data) {
            super(R.layout.dialog_city_list_item, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, City item) {
            TextView cityName = helper.getView(R.id.city_name);
            cityName.setText(item.getValue());

            RxView.clicks(cityName).subscribe(o -> {
                String content = mBinding.tvContent.getText().toString();
                if (Check.isEmpty(content)) {
                    mBinding.tvContent.setText(item.getValue());
                } else {
                    mBinding.tvContent.setText(mBinding.tvContent.getText().toString() + "  " + item.getValue());
                }
                if (count == 3) {
                    Intent intent = new Intent();
                    intent.putExtra("cityName",  mBinding.tvContent.getText().toString());
                    intent.putExtra("cityId", cityId);
                    getTargetFragment().onActivityResult(REUEST_CODDE, Activity.RESULT_OK, intent);
                    dismiss();
                }
                getCity(item.getId());
            });
        }
    }

    /**
     * 获得城市列表
     */
    public void getCity(int id) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("type", 1);
        if (!Check.isEmpty(cities)) {
            map.put("idStr", id);
        }
        HttpRequest.getInstance().createService(APIService.class)
                .selectRegion(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError(throwable -> LogUtil.e(throwable.getMessage()))
                .subscribe(cityHttpResult -> {
                    LogUtil.e("获得城市列表：" + new Gson().toJson(cityHttpResult.getData()));
                    if (cityHttpResult.getCode() == 200) {
                        count++;
                        List<City> cityList = cityHttpResult.getData();
                        if (!Check.isEmpty(cityList)) {

                            cities.clear();
                            cities.addAll(cityList);
                            adapter.setNewData(cities);
                        }
                    } else {
                        ToastUtils.error(cityHttpResult.getMsg());
                    }
                });
    }


}
